<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useLoading } from '@sa/hooks';
import { fetchCreateIdentityConfig, fetchUpdateIdentityConfig } from '@/service/api/business/identity-config';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'IdentityConfigOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Business.IdentityConfig | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule, patternRules } = useFormRules();
const { loading: submitLoading, startLoading, endLoading } = useLoading();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增身份核验配置',
    edit: '编辑身份核验配置'
  };
  return titles[props.operateType];
});

type Model = Api.Business.IdentityConfigOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: '',
    appId: '',
    name: '',
    idCard: '',
    apIds: '',
    status: 0
  };
}

type RuleKey = Extract<
  keyof Model,
  'appId' | 'apIds' | 'status'
>;

const rules: Record<RuleKey, App.Global.FormRule | App.Global.FormRule[]> = {
  appId: createRequiredRule('appId不能为空'),
  // name: createRequiredRule('名称不能为空'),
  // idCard: [createRequiredRule('身份证不能为空'), { ...patternRules.idCard, trigger: ['blur', 'change'] }],
  apIds: createRequiredRule('产品ID不能为空'),
  status: createRequiredRule('状态不能为空')
};

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  startLoading();

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateIdentityConfig(model);
    if (error) {
      endLoading();
      return;
    }
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateIdentityConfig(model);
    if (error) {
      endLoading();
      return;
    }
  }

  endLoading();
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="600" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NDivider>基本信息</NDivider>
        <NFormItem label="App ID" path="appId">
          <NInput v-model:value="model.appId" placeholder="请输入App ID" />
        </NFormItem>
        <NFormItem label="产品ID" path="apIds">
          <NInput v-model:value="model.apIds" placeholder="请输入产品ID" />
        </NFormItem>
<!--        <NFormItem label="名称" path="name">-->
<!--          <NInput v-model:value="model.name" placeholder="请输入名称" />-->
<!--        </NFormItem>-->
<!--        <NFormItem label="身份证" path="idCard">-->
<!--          <NInput v-model:value="model.idCard" placeholder="请输入身份证号码" />-->
<!--        </NFormItem>-->
        <NFormItem label="状态" path="status">
          <DictRadio v-model:value="model.status" dict-code="sys_normal_disable" />
        </NFormItem>

      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
